#!/usr/bin/python
#coding: utf-8
"""
@Name:04_ssh登录模块paramiko.py
@Data:20-5-3
@Author:181
"""
import  paramiko
def login_ssh_passwd(host,port,user,password,command):

    with paramiko.SSHClient() as client:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host,
                       port=port,
                       username=user,
                       password=password)
        #连接成功执行命令

        stdin, stdout,stderr = client.exec_command(command)
        #print(stdout.read().decode('utf-8'))
        return  stdout.read().decode('utf-8')

def login_ssh_key(host, port, user, keyfile, command):
    # 实例化SSH客户端对象
    with paramiko.SSHClient() as client:
        # 配置私人密钥文件位置
        private = paramiko.RSAKey.from_private_key_file(keyfile)
        # 自动添加当前主机到远程服务器的known_hosts, 远程连接不需要再问yes/no
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 通过用户名和密码连接远程服务器,
        client.connect(
            hostname=host,
            port=port,
            username=user,
            pkey=private
        )
        # 连接成功后执行命令
        stdin, stdout, stderr = client.exec_command(command)
        return stdout.read().decode('utf-8')



if __name__ == '__main__':
    # result = login_ssh_passwd('172.25.135.13',22,'root','redhat','hostname')
    # print(result)
    result = login_ssh_passwd('172.25.135.13', 22, 'root', 'id_rsa', 'hostname')
    print(result)